<?php
namespace app\index\model;
use app\index\model\Defend;
use app\index\model\IpLocation;

class Rule{
    /**
     *
     * @var type 
     */
    public $Defend;
    //
    private function __construct(){
        $this->Defend = Defend::instance();
    }
    //
    public static function instance(){
        return new Rule();
    }
    /**
     * 页面显示规则
     * @param array $param ['user_agent', 'skip', 'deny', 'banbase', 'banpc', 'baids', 'ip'];
     * @param type $blockip
     * @return array [0未设置1全局屏蔽2电脑端屏蔽3关键字屏蔽|4客户端屏蔽|5运营商屏蔽|6地区屏蔽|7|8IP黑名单屏蔽]
     */
    public function run($param, $blockip = null){
        $resp = ['deny' => false, 'types' => 0];
        if($param['skip'] == 1){
            return $resp;
        }
        if($blockip && $blockip['act'] == 1){//ip黑名单
            $resp = ['deny' => true, 'types' => 8];
            return $resp;
        }elseif($param['deny'] == 1){//全局
            $resp = ['deny' => true, 'types' => 1];
            return $resp;
        }
        if($param['banpc'] == 1 && !$this->Defend->isMobile($param['user_agent'])){//电脑端
            $resp = ['deny' => true, 'types' => 2];
            return $resp;
        }
        if($this->Defend->inKeyword($param['user_agent'])){//客户端关键字
            $resp = ['deny' => true, 'types' => 3];
            return $resp;
        }
        if($this->Defend->isDenyUA($param['user_agent'], $param['tname'])){//完整客户端
            $resp = ['deny' => true, 'types' => 4];
            return $resp;
        }
        if($param['baids'] && $param['ip']){
            $location = IpLocation::instance()->get($param['ip']);
            $isp = $location['isp'];
            unset($location['isp']);
            if($isp && $this->Defend->isNet($isp)){//运营商
                $resp = ['deny' => true, 'types' => 5, 'location' => $location, 'isp' => $isp];
                return $resp;
            }
            $resp = ['deny' => false, 'types' => 6, 'location' => $location, 'isp' => $isp];
            if($this->Defend->isArea($location, $param['baids'])){//地区
                $resp['deny'] = true;
            }
        }
        return $resp;
    }
}